const KEY = 'diaries';

function getDiaries(): { [key: string]: any } {
  const diaries = wx.getStorageSync(KEY) || {};
  return diaries;
}

function setDiaries(diaries: { [key: string]: any }) {
  wx.setStorageSync(KEY, diaries);
}

function addDiary(diary: { content: string, date: string, imagePath?: string, mood: string }) {
  const diaries = getDiaries();
  const id = new Date().toISOString(); // 使用时间戳作为唯一标识
  diaries[id] = diary;
  setDiaries(diaries);
}

function removeDiary(id: string) {
  const diaries = getDiaries();
  delete diaries[id];
  setDiaries(diaries);
}

Page({
  data: {
    content: '',
    isEditing: false,
    mood: 'positive', // 默认为正向情绪
    imagePath: ''
  },

  onLoad: function (options) {
    if (options.id) {
      this.setData({ isEditing: true });
      const diaries = getDiaries();
      const id = options.id;
      const diary = diaries[id];
      if (diary) {
        this.setData({ content: diary.content, imagePath: diary.imagePath || '', mood: diary.mood || 'positive' });
      }
    }
  },

  onContentInput: function (e: WechatMiniprogram.Input) {
    this.setData({ content: e.detail.value });
  },

  toggleMood: function (e) {
    const mood = e.currentTarget.dataset.mood;
    this.setData({
      mood: mood
    });
  },

  chooseImage: function () {
    wx.chooseImage({
      count: 1, // 限制选择一张图片
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({ imagePath: tempFilePaths[0] });
      },
      fail: (err) => {
        console.error('选择图片失败', err);
      }
    });
  },

  saveDiary: function () {
    if (this.data.content) {
      // 确保已选择图片  
      if (!this.data.imagePath) {
        wx.showToast({
          title: '请先选择一张图片',
          icon: 'none',
          duration: 2000
        });
        return; // 退出 saveDiary 方法，防止继续执行  
      }

      const diary = {
        content: this.data.content,
        date: new Date().toISOString(), // 获取当前时间  
        mood: this.data.mood
      };

      // 准备发送日记数据  
      const username = 'your_username'; // 替换为实际用户名  
      const password = 'your_password'; // 替换为实际密码  

      // 创建一个对象来存储表单数据  
      const formData = {
        username: username,
        password: password,
        diary: JSON.stringify(diary) // 将日记对象转换为字符串  
      };

      // 上传图片和表单数据  
      wx.uploadFile({
        url: 'http://127.1.0.3:5001/api/upload',
        filePath: this.data.imagePath, // 从数据中获取图像路径  
        name: 'file', // 此参数应与Flask服务器的request.files['file']相匹配  
        formData: formData,
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.message) {
            wx.showToast({
              title: '日记保存成功',
              icon: 'success',
              duration: 2000
            });
            setTimeout(() => {
              wx.redirectTo({
                url: '../diaryList/diaryList'
              });
            }, 2000);
          } else {
            wx.showToast({
              title: '保存失败，请重试',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('请求失败：', err);
          wx.showToast({
            title: '请求失败，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    } else {
      wx.showToast({
        title: '请填写内容',
        icon: 'none',
        duration: 2000
      });
    }
  }
});